package com.first.community.service;

import com.first.community.dto.PaginationDTO;
import com.first.community.dto.QuestionDTO;
import com.first.community.dto.QuestionQueryDTO;
import com.first.community.exception.CustomizeErrorCode;
import com.first.community.exception.CustomizeExcetpion;
import com.first.community.mapper.QuestionExtMapper;
import com.first.community.mapper.QuestionMapper;
import com.first.community.mapper.UserMapper;
import com.first.community.model.Question;
import com.first.community.model.QuestionExample;
import com.first.community.model.User;
import com.first.community.model.UserExample;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class QuestionService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private QuestionMapper questionMapper;


    @Autowired
    private QuestionExtMapper questionExtMapper;


    public PaginationDTO getQuestionDTO(String search,Integer page, Integer size) {

        List<QuestionDTO> questionDTOList = new ArrayList<>();
        PaginationDTO paginationDTO = new PaginationDTO();
        QuestionQueryDTO questionQueryDTO = new QuestionQueryDTO();
        String regexp = null;
        if(search!=null){
            String[] split = search.split(" ");
             regexp = Arrays.stream(split).collect(Collectors.joining("|"));
        }
        questionQueryDTO.setSize(size);
        questionQueryDTO.setSearch(regexp);
        Integer totalCount = questionExtMapper.countBySearch(questionQueryDTO);
        //计算totalPage
        //计算页面个数
        if(totalCount%size==0) {
            paginationDTO.setTotalPage(totalCount/size);
        }else{
            paginationDTO.setTotalPage(totalCount/size+1);
        }
        //page修正
        if(page<1){
            page=1;
        }
        if(page>paginationDTO.getTotalPage()){
            page=paginationDTO.getTotalPage();
        }
        Integer offset= page<=0?0:size*(page-1);
        questionQueryDTO.setPage(offset);

        //正则匹配搜索内容
        List<Question> questionList= questionExtMapper.selectBySearch(questionQueryDTO);

        for (Question question : questionList) {
            UserExample example = new UserExample();
            example.createCriteria()
                    .andIdEqualTo(question.getCreator());
            List<User> users = userMapper.selectByExample(example);
            User user=null;
            if(users.size()==0){
               user=null;
            }else {
                user = users.get(0);
            }
            QuestionDTO questionDTO = new QuestionDTO();
            BeanUtils.copyProperties(question,questionDTO);
            questionDTO.setUser(user);
            questionDTOList.add(questionDTO);
        }
        paginationDTO.setData(questionDTOList);
        paginationDTO.setPagination(totalCount,page,size);



        return  paginationDTO;
    }

    public PaginationDTO list(Long id, Integer page, Integer size) {


        List<QuestionDTO> questionDTOList = new ArrayList<>();
        PaginationDTO paginationDTO = new PaginationDTO();
        QuestionExample questionExample1 = new QuestionExample();
        questionExample1.createCriteria()
                .andCreatorEqualTo(id);
        Integer totalCount = (int) questionMapper.countByExample(questionExample1);
        //计算totalPage
        //计算页面个数
        if(totalCount%size==0) {
            paginationDTO.setTotalPage(totalCount/size);
        }else{
            paginationDTO.setTotalPage(totalCount/size+1);
        }


        //page修正
        if(page<1){
            page=1;
        }
        if(page>paginationDTO.getTotalPage()){
            page=paginationDTO.getTotalPage();
        }
        Integer offset= size*(page-1);


        QuestionExample questionExample = new QuestionExample();
        questionExample.createCriteria()
                .andCreatorEqualTo(id);
        List<Question> questionList=questionMapper.selectByExampleWithBLOBsWithRowbounds(questionExample,new RowBounds(offset,size));
        for (Question question : questionList) {
            UserExample example = new UserExample();
            example.createCriteria()
                    .andIdEqualTo(question.getCreator());
            List<User> users = userMapper.selectByExample(example);
            User user=users.get(0);
            QuestionDTO questionDTO = new QuestionDTO();
            BeanUtils.copyProperties(question,questionDTO);
            questionDTO.setUser(user);
            questionDTOList.add(questionDTO);
        }
        paginationDTO.setData(questionDTOList);
        paginationDTO.setPagination(totalCount,page,size);



        return  paginationDTO;


    }

    public QuestionDTO getById(Long number) {
        QuestionDTO questionDTO = new QuestionDTO();
        Question question = new Question();

        QuestionExample example = new QuestionExample();
        example.createCriteria()
                .andIdEqualTo(number);
        List<Question> questionList = questionMapper.selectByExampleWithBLOBs(example);

        if(questionList.size()!=0){
            question=questionList.get(0);
        }else{
            throw  new CustomizeExcetpion(CustomizeErrorCode.QUESTION_NOT_FOUND);
        }

        BeanUtils.copyProperties(question,questionDTO);

        UserExample example1 = new UserExample();
        example1.createCriteria()
                .andIdEqualTo(question.getCreator());
        List<User> users = userMapper.selectByExample(example1);

        User user = null;
        if(users.size()!=0){
            user= users.get(0);
        }

        questionDTO.setUser(user);

        return  questionDTO;

    }

    public void CreateOrUpdate(Question question) {

        if(question.getId()==null){
            questionMapper.insert(question);
        }else{
            QuestionExample example = new QuestionExample();
            example.createCriteria()
                    .andIdEqualTo(question.getId());
            int update=questionMapper.updateByExampleWithBLOBs(question, example);
            if(update!=1){
                throw  new CustomizeExcetpion(CustomizeErrorCode.QUESTION_NOT_FOUND);
            }
        }
    }

    public void addViewCount(Long id) {
        Question question = new Question();
        question.setId(id);
        question.setViewCount(1);
        questionExtMapper.incView(question);
    }

    public List<QuestionDTO> selectByTag(QuestionDTO questionDTO) {
        Question questionTool = new Question();
        String[] split = questionDTO.getTag().split(",");
        String regexp = Arrays.stream(split).collect(Collectors.joining("|"));
        questionTool.setTag(regexp);
        questionTool.setId(questionDTO.getId());
        List<Question> relatedQuestions = questionExtMapper.getRelated(questionTool);
        List<QuestionDTO> relatedQuestionDTOs = relatedQuestions.stream().map(q -> {
            QuestionDTO relatedQuestionDTO = new QuestionDTO();
            BeanUtils.copyProperties(q, relatedQuestionDTO);
            return relatedQuestionDTO;
        }).collect(Collectors.toList());
        return relatedQuestionDTOs;
    }
}

